<template>
  <div id="projectTosComponent">

    <div name="开发信息提示" v-if="isInDevMode">
      queryParams: {{ queryParams }}
    </div>


    <!--查询框-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px"
             @keyup.enter.native="handleQuery">
      <!-- 项目类型 -->
      <span v-show="showSearch">
      <el-form-item label="项目类型">
        <el-select v-model="queryParams.projectTypeList" placeholder="请选择项目类型" multiple>
          <el-option
            v-for="item in dict.type.project_type"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!--companyCod,从companyCodeOptions中选择，例如：{"key":"YFG","value":"YFG","label":"云浮港","remark":null}-->
      <el-form-item label="码头">
        <el-select v-model="queryParams.companyCod" placeholder="请选择码头" @change="handleQuery" clearable>
          <el-option
            v-for="item in companyCodeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 预约号 -->
      <el-form-item label="预约号">
        <el-input v-model="queryParams.reservationNo" placeholder="请输入预约号" clearable></el-input>
      </el-form-item>
      <!-- 船名 -->
      <el-form-item label="船名">
        <el-select v-model="queryParams.shipNam" placeholder="请选择船名" @change="handleQuery" clearable filterable>
          <el-option
            v-for="item in shipNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 航次 -->
      <el-form-item label="航次">
        <el-select v-model="queryParams.voyage" placeholder="请选择航次" @change="handleQuery" clearable filterable>
          <el-option
            v-for="item in voyageOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 提单号 -->
      <el-form-item label="提单号">
        <el-input v-model="queryParams.billNo" placeholder="请输入提单号" clearable></el-input>
      </el-form-item>
      <!-- 货名 -->
      <el-form-item label="货名">
        <el-input v-model="queryParams.cargoName" placeholder="请输入货名" clearable></el-input>
      </el-form-item>
      <!-- 集装箱号 -->
      <el-form-item label="集装箱号">
        <el-input v-model="queryParams.containerNo" placeholder="请输入集装箱号" clearable></el-input>
      </el-form-item>
      <!--开始时间-结束时间-->
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          range-separator="至"
          value-format="yyyy-MM-dd"
          :picker-options="dateRangePickerOptions"
          @change="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <!--进出口类型-->
      <el-form-item label="进出口">
        <el-select v-model="queryParams.ieType" placeholder="请选择进出口类型" @change="handleQuery" clearable>
          <el-option
            v-for="item in dict.type.ie_type"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!--CUSTOMER_NAM 结算客户名称-->
      <el-form-item label="客户名称">
        <el-select v-model="queryParams.customerNam" placeholder="请选择结算客户名称" @change="handleQuery" clearable
                   filterable>
          <el-option
            v-for="item in customerNameOptions"
            :key="item.index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--计费状态-->
      <el-form-item label="绑定状态">
        <el-select v-model="queryParams.chargeStatus" placeholder="请选择绑定状态" @change="handleQuery" clearable>
          <el-option
            v-for="item in dict.type.charge_status"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!--结算方式-->
      <el-form-item label="结算方式">
        <el-select v-model="queryParams.feeWay" placeholder="请选择结算方式" @change="handleQuery" clearable>
          <el-option
            v-for="item in dict.type.fee_way"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 业务数据摘要 -->
      <el-form-item label="业务摘要">
        <el-input v-model="queryParams.projectData" placeholder="请输入业务数据摘要" clearable></el-input>
      </el-form-item>

      <!--按钮组-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQueryParams">重置</el-button>
      </el-form-item>
      <!--一键绑定合同-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-plus" size="mini"
                   :disabled="selectedTosProjectViews.length === 0"
                   @click="handleOneKeyBindContract">一键绑定合同
        </el-button>
      </el-form-item>

      <!--一解绑合同-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="el-icon-circle-close" size="mini"-->
<!--                   :disabled="selectedTosProjectViews.length === 0"-->
<!--                   @click="handleOneKeyUnBindContract">解绑合同-->
<!--        </el-button>-->
<!--      </el-form-item>-->
      </span>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

    </el-form>


    <div name="开发信息提示" v-if="isInDevMode">
      tosProjectViewList: {{ tosProjectViewList[0] }}
      <hr/>
      selectedTosProjectViews: {{ selectedTosProjectViews[0] }}
      <hr/>
    </div>

    <!--table-->
    <el-table v-loading="loading"
              :data="tosProjectViewList"
              @selection-change="handleSelectionChange"
              @current-change="handleRowClick"
              default-expand-all
              width="100%"
              height="300px"
              highlight-current-row
              :row-class-name="rowClassNameByCollectionStatus"
              border
              size="mini" style="width: 100%"
              ref="tosProjectViewTable">
      <el-table-column type="selection" align="center"/>
      <el-table-column label="计费类型" prop="projectType" v-if="isInDevMode" align="center" show-overflow-tooltip/>
      <el-table-column label="计费类型名称" prop="projectTypeName" align="center" show-overflow-tooltip width="100px"/>
      <el-table-column label="结费客户代码" prop="customerCod" v-if="isInDevMode" align="center" show-overflow-tooltip/>
      <el-table-column label="结费客户名称" prop="customerNam" align="center" show-overflow-tooltip width="100px"/>
      <el-table-column label="预约号" prop="reservationNo" align="center" show-overflow-tooltip/>
      <el-table-column label="船名" prop="shipNam" align="center" show-overflow-tooltip/>
      <el-table-column label="航次" prop="voyage" align="center" show-overflow-tooltip/>
      <el-table-column label="进出口" prop="ieType" align="center" show-overflow-tooltip
                       :formatter="ieTypeFormatter"/>
      <el-table-column label="提单号" prop="billNo" align="center" show-overflow-tooltip/>
      <el-table-column label="集装箱号" prop="containerNo" align="center" show-overflow-tooltip/>
      <el-table-column label="货名" prop="cargoName" align="center" show-overflow-tooltip/>
      <el-table-column label="业务开始时间" prop="startTime" align="center" show-overflow-tooltip width="100px"/>
      <el-table-column label="业务结束时间" prop="endTime" align="center" show-overflow-tooltip width="100px"/>
      <el-table-column label="业务数据摘要" prop="projectData" align="center" show-overflow-tooltip width="200px"/>
      <el-table-column label="结算方式" prop="feeWay" align="center" show-overflow-tooltip/>
      <el-table-column label="绑定状态" prop="chargeStatus" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.chargeStatus == 0">未绑定</span>
          <span v-if="scope.row.chargeStatus == 1">已绑定</span>
        </template>
      </el-table-column>
      <el-table-column label="项目ID" prop="projectId" align="center" show-overflow-tooltip/>
<!--      <el-table-column label="合同ID" prop="conId" align="center" show-overflow-tooltip/>-->
      <el-table-column label="合同" prop="conCode" align="center" show-overflow-tooltip width="180px"/>
      <el-table-column label="gkey" prop="gkey" align="center" v-if="isInDevMode" show-overflow-tooltip/>
      <el-table-column label="码头" prop="companyCod" align="center" v-if="isInDevMode" show-overflow-tooltip/>
      <el-table-column label="作业点" prop="cfsCod" align="center" v-if="isInDevMode" show-overflow-tooltip/>
    </el-table>


    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>

import {listVProjectTos, oneKeyBindContract,unBindContract} from "@/api/business/vProjectTos";
import queryParamsLocalStorageMixin from "@/mixin/queryParam/queryParamsLocalStorageMixin";
import tosWorkPlaceOptionsMixin from "@/mixin/tos/tosWorkPlaceOptionsMixin";
import dict from "@/utils/dict";
import customerNameOptionsMixin from "@/mixin/tos/customerNameOptionsMixin";
import {shipNameOptionsMixin} from "@/mixin/tos/shipNameOptionsMixin";
import {voyageOptionsMixin} from "@/mixin/tos/voyageOptionsMixin";

export default {
  name: "ProjectTosComponent",
  mixins: [queryParamsLocalStorageMixin, tosWorkPlaceOptionsMixin, customerNameOptionsMixin, shipNameOptionsMixin, voyageOptionsMixin],
  dicts: ['project_type', 'ie_type', 'charge_status','fee_way'],
  data() {
    return {
      // 作弊码：从localStorage中获取是否处于开发模式，值为true或false
      isInDevMode: localStorage.getItem('isInDevMode') === 'true',

      // mixin中的属性：queryParamsLocalStorageKey 用于存储查询参数的localStorage的key
      queryParamsLocalStorageKey: 'ProjectTosComponent.queryParams',


      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tosProjectViewList: [],
      // 勾选的数据
      selectedTosProjectViews: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 时间范围 picker 的选项设置
      dateRangePickerOptions: {
        shortcuts: [{
          text: '昨天今天',
          onClick(picker) {
            const start = new Date()
            const end = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '今天',
          onClick(picker) {
            const start = new Date()
            const end = new Date()
            // start.setTime(start.getTime()-3600*1000*24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

    };
  },
  computed: {

    // 勾选的tosProjectView的关键字组合：采用gkey+projectType
    selectedTosProjectViewsCombination() {
      return this.selectedTosProjectViews.map(item => ({
        projectTypeName: item.projectTypeName,
        gkey: item.gkey,
      }));
    },


  },
  created() {
    // 获取table数据
    // this.getList();
  },
  methods: {
    /** 获取列表数据 */
    async getList() {
      // 显示遮罩层
      this.loading = true;
      // 获取后台数据
      const response = await listVProjectTos(this.queryParams);
      this.tosProjectViewList = response.rows;
      this.total = response.total;
      // 隐藏遮罩层
      this.loading = false;
    },

    /** 解绑合同 */
    async handleOneKeyUnBindContract() {
      // 记录勾选的数据（记录row里面的关键字组合，而不是projectId），用于绑定合同成功后重新勾选，简化用户操作
      // 因为请求前 勾选的数据没有projectId，但是重新getList后，勾选的数据有projectId，因此用关键字组合来定位
      // 是从computed中获取的，const固定一下。
      const lastSelectedCombinationList = this.selectedTosProjectViewsCombination;

      // 发送请求，一键绑定合同
      const response = await unBindContract(this.selectedTosProjectViews);

      // 根据响应结果，提示用户
      if (response.code === 200) {
        // 一键绑定合同成功
        this.$message.success(response.msg);
      } else {
        // 一键绑定合同失败
        this.$message.error(response.msg);
      }

      // 刷新列表
      await this.getList();

      // 在获取最新数据后，重新勾选匹配的行数据
      // 清空勾选
      this.$refs.tosProjectViewTable.clearSelection();
      // 找出需要勾选的行数据
      const selectedRows = this.tosProjectViewList.filter(item => {
        // 当前行的关键字组合（gkey+projectType）
        const currentCombination = {
          projectTypeName: item.projectTypeName,
          gkey: item.gkey,
        };
        // 判断当前行的关键字组合是否在上次勾选的数据中
        return lastSelectedCombinationList.some(combination =>
          this.areKeywordCombinationsEqual(combination, currentCombination)
        );
      });
      // 执行勾选
      // 由于勾选ids变化，子组件会watch到，所以会自动重新查询projectIds对应的收款
      selectedRows.forEach(row => {
        this.$refs.tosProjectViewTable.toggleRowSelection(row, true);
      });
    },

    /** 一键绑定合同 */
    async handleOneKeyBindContract() {
      this.loading = true
      // 记录勾选的数据（记录row里面的关键字组合，而不是projectId），用于绑定合同成功后重新勾选，简化用户操作
      // 因为请求前 勾选的数据没有projectId，但是重新getList后，勾选的数据有projectId，因此用关键字组合来定位
      // 是从computed中获取的，const固定一下。
      const lastSelectedCombinationList = this.selectedTosProjectViewsCombination;

      // 发送请求，一键绑定合同
      const response = await oneKeyBindContract(this.selectedTosProjectViews);

      // 根据响应结果，提示用户
      if (response.code === 200) {
        // 一键绑定合同成功
        this.$message.success(response.msg);
      } else {
        // 一键绑定合同失败
        this.$message.error(response.msg);
      }
      this.loading = false

      // 刷新列表
      await this.getList();

      // 在获取最新数据后，重新勾选匹配的行数据
      // 清空勾选
      this.$refs.tosProjectViewTable.clearSelection();
      // 找出需要勾选的行数据
      const selectedRows = this.tosProjectViewList.filter(item => {
        // 当前行的关键字组合（gkey+projectType）
        const currentCombination = {
          projectTypeName: item.projectTypeName,
          gkey: item.gkey,
        };
        // 判断当前行的关键字组合是否在上次勾选的数据中
        return lastSelectedCombinationList.some(combination =>
          this.areKeywordCombinationsEqual(combination, currentCombination)
        );
      });
      // 执行勾选
      // 由于勾选ids变化，子组件会watch到，所以会自动重新查询projectIds对应的收款
      selectedRows.forEach(row => {
        this.$refs.tosProjectViewTable.toggleRowSelection(row, true);
      });
    },

    /** 判断两个关键字组合是否相等，用于一键绑定合同成功后重新勾选 */
    areKeywordCombinationsEqual(combination1, combination2) {
      // 检查关键字组合是否相等的帮助函数
      return (
        combination1.projectTypeName === combination2.projectTypeName &&
        combination1.gkey === combination2.gkey
      );
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 行点击事件 */
    handleRowClick(row) {
      this.$emit('rowClick', row);
    },
    /** 勾选数据变化 */
    handleSelectionChange(selection) {
      this.selectedTosProjectViews = selection;

      this.$emit('selectionChange', selection);
    },
    /** 重置搜索条件 */
    resetQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        chargeStatus: '0',
      };
      this.handleQuery();
    },
    /** 根据计费状态返回行的类名 */
    rowClassNameByCollectionStatus({row, rowIndex}) {
      return row.chargeStatus === 1 ? 'row-charged' : '';
    },
    /** ie_type 的formatter */
    ieTypeFormatter(row, column) {
      return this.selectDictLabel(this.dict.type.ie_type, row.ieType);
    },
  }

};
</script>


<style>

/** 已经收款的行的背景色 */
.row-charged {
  background-color: rgb(240, 249, 235) !important;
}


</style>
